<template>
  <div>
    <el-card class="search-card">
      <el-form class="header-fields-wrap" label-width="100px">
        <el-row
          v-for="(rowNum, rowIndex) in totalRowNum"
          :key="rowIndex"
          :gutter="24"
        >
          <el-col
            v-show="hasReason(item)"
            v-for="(item, index) in headerField.itemList.slice(
              rowIndex * headerField.colNumOfRow,
              rowNum * headerField.colNumOfRow
            )"
            :key="item.prop + index"
            :span="24 / headerField.colNumOfRow"
          >
            <el-form-item :label="`${item.label}：`">
              <span>{{ headerField.dataSource[item.prop] }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-tabs v-model="elTabs.value" @tab-click="handleChangeTabs">
        <el-tab-pane
          v-for="(item, index) in elTabs.list"
          :key="item.label + index"
          :label="item.label"
          :name="item.name"
        ></el-tab-pane>
      </el-tabs>
      <el-row>
        <SkusTable
          :loading="tableInfo.loading"
          :data-source="tableInfo.list"
          :columns="tableInfo.columns"
        />
      </el-row>
    </el-card>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import SkusTable from '@/components/skusTable';
import {
  tabsList,
  headerFieldsList,
  goodsInfoColumns,
  purchaseInfoColumns,
  purchaseSteelInfoColumns,
  saleInfoColumns,
  saleSteelInfoColumns,
  acceptStandardInfoColumns
} from '../constants/viewRecord';
/* utils */
import { isResponseSuccess } from '@/utils/bizUtils';
import { getFooterFieldFn } from '@/pages/commodity/modules/utils';
import { VIEW_RECORD_TABLE_COLUMNS as NEW_SALE_TABLE_COLUMNS } from '@/constants/salePrice';
import { isBeforeRecordDate } from '@/utils/salePrice';

export default {
  components: {
    SkusTable
  },
  data () {
    return {
      elTabs: {
        list: tabsList,
        value: '1'
      },
      tableInfo: {
        list: [],
        columns: [],
        loading: false
      },
      headerField: {
        itemList: headerFieldsList,
        dataSource: {},
        colNumOfRow: 4 // 每行字段个数
      },
      apiObj: {
        // 查看单据的信息
        getByRecordNo: {
          url: '/sysback/commit/record/getByRecordNo', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 查看单据详情
        getDetailByRecordNo: {
          url: '/sysback/product/addSku/recordInfo/getSpuAddSkuRecordDetailByRecordNo',
          type: 'post' // 接口请求类型
        },
        // 查看tabs
        getDetailByRecordTab: {
          url: '/sysback/commit/record/showRecordTab',
          type: 'post' // 接口请求类型
        },
        // 查看新售价单据详情
        searchRecordForAddSku: {
          url: '/sysback/salePrice/secondPhase/prepare/searchRecordForAddSku',
          type: 'get'
        }
      }
    };
  },
  created () {
    const { recordNo } = this.$route.query;
    this.tableInfo.columns = goodsInfoColumns;
    this.getTabsInfoFn(recordNo);
    this.getTableDataFn(recordNo, '1');
    this.getHeaderFieldsFn(recordNo);
  },
  computed: {
    /* 总行数 */
    totalRowNum () {
      return Math.ceil(this.headerField.itemList.length / this.headerField.colNumOfRow);
    },
  },
  methods: {
    // 是否含有原因字段
    hasReason (item) {
      if (item.prop !== 'reason') { // 不是reason字段默认展示
        return true;
      }
      if (this.headerField.dataSource.reason) {
        return true;
      }
      return false;
    },
    // 获取tabs展示信息
    async getTabsInfoFn (recordNo) {
      const data = {};
      const { url, type } = this.apiObj.getDetailByRecordTab;
      const res = await ApiRequest(`${url}?recordNo=${recordNo}`, type, data);
      if (isResponseSuccess(res)) {
        const defaultTab = ['1', '6'];
        const asyncTabs = res.retData ? res.retData.concat(defaultTab) : defaultTab;
        const isBeforeRecord = isBeforeRecordDate(recordNo)
        if (!isBeforeRecord) asyncTabs.push('7')
        this.elTabs.list = this.elTabs.list.filter(item => asyncTabs.includes(item.name));
      }
    },
    // 获取表头字段数据
    async getHeaderFieldsFn (recordNo) {
      const data = { recordNo };
      const { url, type } = this.apiObj.getByRecordNo;
      const res = await ApiRequest(`${url}?recordNo=${recordNo}`, type, data);
      if (isResponseSuccess(res)) {
        this.headerField.dataSource = getFooterFieldFn(res.retData);
      }
    },
    // 获取表格数据
    async getTableDataFn (recordNo, index) {
      let data = {};
      let requestApi = this.apiObj.getDetailByRecordNo
      if (this.elTabs.value == '7') { // 新售价
        requestApi = this.apiObj.searchRecordForAddSku
      }
      const { url, type } = requestApi;
      const apiUrl = `${url}?recordNo=${recordNo}&contentType=${index}`;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(apiUrl, type, data);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          this.tableInfo.list = this.dealTableDataFn(res.retData);
          if (index === '6') {
            this.tableInfo.list = this.formatTableData(res.retData);
          }
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 切换tabs
    handleChangeTabs () {
      const columnsMapping = {
        '1': goodsInfoColumns,
        '2': purchaseInfoColumns,
        '3': purchaseSteelInfoColumns,
        '4': saleInfoColumns,
        '5': saleSteelInfoColumns,
        '6': acceptStandardInfoColumns,
        '7': NEW_SALE_TABLE_COLUMNS
      }
      this.tableInfo.columns = columnsMapping[this.elTabs.value] || [];
      this.getTableDataFn(this.headerField.dataSource.recordNo, this.elTabs.value);
    },
    // 处理表格数据
    dealTableDataFn (dataSource) {
      return dataSource && dataSource.reduce((value, item) => {
        let row = {};
        if (item.business1) {
          row = {
            ...item,
            ...JSON.parse(item.business1)
          }
        } else {
          row = item;
        }
        value.push(row);
        return value;
      }, []);
    },
    // 格式化表格数据
    formatTableData (reData) {
      let tableData = [];
      reData.forEach((element, oneIndex) => {
        // 准备一行数据的普通列
        let curRow = {
          productName: element.productName,
          brandName: element.brandName,
          categoryName: element.categoryName,
          spuNo: element.spuNo,
          skuNo: element.skuNo,
          checkTime: element.checkTime,
          specDetailStr: element.specDetailStr,
          checkFrequency: element.checkFrequency,
          itemList: element.itemList
        };
        // 新建表头。并准备一行数据的动态列
        element.itemList.forEach((item, index) => {
          this.pushItem(oneIndex, curRow, item, index);
        });
        // 将行，添加到展示列表
        tableData.push(curRow);
      });
      return tableData;
    },
    // 特殊处理表列
    pushItem (oneIndex, curRow, innerEle, index) {
      const checkCount = {
        title: '验收次数',
        align: 'center',
        key: 'checkCount' + index,
      }
      const standardValue = {
        title: '标准值',
        align: 'center',
        key: 'standardValue' + index,
      }
      const upDiffValue = {
        title: '上差值',
        align: 'center',
        key: 'upDiffValue' + index,
      }
      const downDiffValue = {
        title: '下差值',
        align: 'center',
        key: 'downDiffValue' + index,
      }
      const checkMethod = {
        title: '验收方法',
        align: 'center',
        key: 'checkMethod' + index,
      }
      // 将行内动态列的信息，平铺到行
      curRow['checkCount' + index] = innerEle.checkCount;
      curRow['standardValue' + index] = innerEle.standardValue;
      curRow['upDiffValue' + index] = innerEle.upDiffValue;
      curRow['downDiffValue' + index] = innerEle.downDiffValue;
      curRow['checkMethod' + index] = innerEle.checkMethod;
      curRow['checkItemType' + index] = innerEle.checkItemType; // 1数字5个列可填，2文本3个列可填
      // 表头，遍历第1行的动态列时，才追加到表头
      if (oneIndex !== 0) { return false; }
      let column = {
        title: innerEle.checkItemName,
        required: innerEle.isNeed === '1',
        key: innerEle.checkItemUuid,
        width: 150,
        align: 'center',
      }
      if (innerEle.checkItemType !== '2') {
        column.children = [checkCount, standardValue, upDiffValue, downDiffValue, checkMethod];
      } else {
        column.children = [checkCount, standardValue, checkMethod]
      }
      this.tableInfo.columns.push(column);
    },
  }
};
</script>
<style lang="less" scoped="scoped">
.header-item {
  margin-right: 100px;
}
.header-fields-wrap {
  .el-col {
    min-height: 10px;
  }
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
